const express = require("express");
const ClassDB = require('../models/User');//用户数据
const categoryClassDB = require('../models/category');//分类数据
const multipart = require("connect-multiparty");//数据处理中间件
const multipartMiddleware = multipart();
const router = express.Router();



// 二级目录路由管理
router.use(function (request,response,next) {
    // 非管理员验证
    if(!request.userinfo.isAdmin){
        response.send('sorry.only root');
        return response;
    }
    next();
});

/*
* 首页管理
* */
router.get('/',function (request,response,next) {
    response.render('admin/index',{
        userinfo:request.userinfo
    });
});

/*
* 用户管理页面
* */
router.get('/user',function (request,response,next) {
    const limit = 2;
    var page = Number(request.query.page || 1);
    var pages = 0;
    // ClassDB对象封装有多种数据库操作方法
    ClassDB.countDocuments().then(function (count) {
        //计算总页数
        pages = Math.ceil(count/limit);
        page = Math.min(page,pages);
        page = Math.max(page,1);
        var skip = (page - 1)*limit;
        ClassDB.find().limit(limit).skip(skip).then(function (data) {
            // console.log(typeof data[0]._id);
            response.render('admin/user_index',{
                userinfo:request.userinfo,
                userData:data,
                count:count,
                pages:pages,
                limit:limit,
                page:page
            });
        });
    });
});

/*
* 分类页面管理
* */
router.get('/category',function (request,response,next) {
    const limit = 20;
    var page = Number(request.query.page || 1);
    var pages = 0;
    // ClassDB对象封装有多种数据库操作方法
    categoryClassDB.countDocuments().then(function (count) {
        //计算总页数
        pages = Math.ceil(count/limit);
        page = Math.min(page,pages);
        page = Math.max(page,1);
        var skip = (page - 1)*limit;
        categoryClassDB.find().sort({_id:-1}).limit(limit).skip(skip).then(function (category) {
            // console.log(typeof data[0]._id);
            response.render('admin/category_index',{
                userinfo:request.userinfo,
                category:category,
                count:count,
                pages:pages,
                limit:limit,
                page:page
            });
        });
    });
});
/*
* 分类页面添加
* */
router.get('/category/add',function (request,response,next) {
    response.render('admin/category_add',{
        userinfo:request.userinfo
    });
});
/*
* 分类页面保存
* */
router.post('/category/add',function (request,response,next) {
    // console.log(request.body);
    var message = {};
    var name = request.body.name || '';
    if(name === ''){
        message.name = '分类名不能为空';
        message.url = 'admin/category';
        response.json(message);
        return response;
    }
    categoryClassDB.findOne({
        name:name
    }).then(function (data) {
        if(data){
            message.url = 'admin/category';
            message.name = '分类名已经存在';
            response.json(message);
            return response;
        }else {
            return new categoryClassDB({
                name:name
            }).save();
        }
    }).then(function (obj) {
        message.url = 'admin/category';
        message.name = '分类保存成功';
        response.json(message);
        return response;
    });

});

//分类页面 get请求入口
router.get('/category/edit',function (request,response) {
    // 获取数据库分类
    var id = request.query.id || '';
    console.log(typeof request.query.id+':'+request.query.id);
    categoryClassDB.findOne({
        _id:id
    }).then(function (category) {
        console.log(category+':get请求成功！');
        if(category){
            response.render('admin/category_edit',{
                userinfo:request.userinfo,
                category:category
            });
        }else {
            response.render('admin/error',{
                userinfo:request.userinfo,
                message:'信息不存在！'
            });
            return Promise.reject();
        }
    });
});

// 分类修改表单提交入口,默认提交的情况下，还是有问题
router.post('/category/edit',function (request,response) {
    var id = request.body.id || '';
    var name = request.body.name || '';
    var returnData = {};
    console.log(name+"===name||||"+id+"===id"+':'+ typeof id);
    categoryClassDB.findOne({
        _id:id
    }).then(function (category) {
        console.log(category+'ccc');
        if(!category){
            /*
            * response.render('admin/error',{
                userinfo:request.userinfo,
                message:'信息不存在！'
            });
            return Promise.reject();
            * */
            returnData.url = 'admin/category';
            returnData.name = '信息不存在！';
            response.json(returnData);
            return response;
        }else {
            if(name===category.name){
                /*
                * response.render('admin/success',{
                    userinfo:request.userinfo,
                    message:'修改成功1',
                    url:'/admin/category'
                });
                return Promise.reject();
                * */
                returnData.url = 'admin/category';
                returnData.name = '分类修改成功1';
                response.json(returnData);
                return response;
            }else{
                return categoryClassDB.findOne({
                    _id:{$ne:id},
                    name:name
                });
            }
        }

    }).then(function (sameData) {
        if(sameData){
            /*
            * response.render('admin/error',{
                userinfo:request.userinfo,
                message:'已有同名信息，换一个吧'
            });
            return Promise.reject();
            * */
            returnData.url = 'admin/category';
            returnData.name = '已有同名信息，换一个吧！';
            response.json(returnData);
            return response;
        }else{
            return categoryClassDB.replaceOne({
                _id:id
            },{
                name:name
            });
        }
    }).then(function () {
        /*
        * response.render('admin/success',{
            userinfo:request.userinfo,
            message:'修改成功2',
            url:'/admin/category'
        });
        * */
        returnData.url = 'admin/category';
        returnData.name = '分类修改成功2';
        response.json(returnData);
        return response;
    });
});

// 删除分类get接口
router.get('/category/delete',function (request,response) {
    var id = request.query.id || '';
    categoryClassDB.remove({
        _id:id
    }).then(function () {
        response.render('admin/success',{
            userinfo:request.userinfo,
            message:'操作成功!'
        });
    });
});

// 内容管理get接口
router.get('/content',function (request,response) {
    response.render('admin/content_index',{
        userinfo:request.userinfo
    });
});

// 内容添加get接口
router.get('/content/add',function (request,response) {
    response.render('admin/content_add',{
        userinfo:request.userinfo
    });
});


module.exports = router;
